package com.af.dao.mobile.impl;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.af.common.CommonUtil;
import com.af.common.GlobalVariables;
import com.af.common.Log4jXmlConfig;
import com.af.common.SignUtil;
import com.af.entity.mobile.Order;

public class ReturnState {
	
	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(ReturnState.class);
	
	private Order order = null;
	
	/**
	 * 返回订单
	 * @param orderNo
	 * @return
	 */
	public Order returnLastOrder(String orderNo) {
		Map params = new LinkedHashMap();
		params.put("agentid", GlobalVariables.ANGETID);
		params.put("backurl", "");
		params.put("returntype", "2");
		params.put("orderid", orderNo);
		params.put("source", GlobalVariables.SOURCE);
		String sign = SignUtil.sign_mobile(params, GlobalVariables.MERCHANTKEY);
		params.put("verifystring", sign);
		String result = new WebService().returnResult(GlobalVariables.MOBIEL_URL+GlobalVariables.DIRECT_SEARCH, params);
		if(CommonUtil.isNotNullOrEmpty(result)){
			order = new Order();
			try {
				Document document = DocumentHelper.parseText(result);
				Element root = document.getRootElement().element("items");
				Element e = null;
				String resultno = null, finishmoney = null;
				for (Iterator i = root.elementIterator(); i.hasNext();) {
					e = (Element) i.next();
					if (e.attribute(0).getValue().equals("resultno")) {
						resultno = e.attribute(1).getValue();
						order.setLastState(Integer.parseInt(resultno));
					}
					if (e.attribute(0).getValue().equals("finishmoney")) {
						finishmoney = e.attribute(1).getValue();
						order.setRealPrice(Double.parseDouble(finishmoney));
					}
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				LOG.error("查询对单NumberFormatException",e);
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				LOG.error("查询对单DocumentException",e);
			}
		}
		return order;
	}
	
}
